package cn.com.mma.mobile.tracking.api;

import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;
import cn.com.mma.mobile.tracking.bean.Argument;
import cn.com.mma.mobile.tracking.bean.Company;
import cn.com.mma.mobile.tracking.bean.SDK;
import cn.com.mma.mobile.tracking.bean.SendEvent;
import cn.com.mma.mobile.tracking.util.CommonUtil;
import cn.com.mma.mobile.tracking.util.DeviceInfoUtil;
import cn.com.mma.mobile.tracking.util.LocationUtil;
import cn.com.mma.mobile.tracking.util.Logger;
import cn.com.mma.mobile.tracking.util.SdkConfigUpdateUtil;
import cn.com.mma.mobile.tracking.util.SharedPreferencedUtil;
import cn.mmachina.JniClient;

/**
 * 记录事件
 * 
 * @author lincoln
 * 
 */
public class RecordEventMessage {
	private Context context;
	private Map<String, String> params;

	public RecordEventMessage(Context context) {
		this.context = context;
		params = DeviceInfoUtil.fulfillTrackingInfo(context);
	}

	private void recordEvent(SendEvent sendEvent) {
		params.put(Global.TRACKING_LOCATION, LocationUtil.getInstance(context).getLocation());
		StringBuilder builder = new StringBuilder();
		String hostUrl = CommonUtil.getHostURL(sendEvent.getUrl());
		SDK sdk = SdkConfigUpdateUtil.getSdk(context);
		if (sdk != null && sdk.companies != null) {
			for (Company company : sdk.companies) {
				if (hostUrl.endsWith(company.domain.url)) {
					List<String> requiredArgmentValue = new ArrayList();
					String separator = "";
					String equalizer = "";
					String redirectURLValue = "";
					for (Argument argument : company.config.arguments) {
						if (argument.isRequired) {
							separator = company.separator;
							equalizer = company.equalizer;
							requiredArgmentValue.add(argument.value);
						}
					}
					Map<String, String> removedExistArgmentAndGetRedirectURL = CommonUtil.removeExistArgmentAndGetRedirectURL(sendEvent.getUrl(),
							requiredArgmentValue, separator, equalizer, redirectURLValue);
					String url = removedExistArgmentAndGetRedirectURL.get(Global.TRACKING_URL);
					builder.append(url);
					String valueAndRedirectURL = "";
					for (Argument argument : company.config.arguments) {
						if (argument.isRequired) {
							if (Global.TRACKING_TIMESTAMP.equals(argument.key)) {
								builder.append(company.separator + argument.value + (company.equalizer != null ? company.equalizer : "")
										+ (company.timeStampUseSecond ? sendEvent.getTimestamp() : sendEvent.getTimestamp()));
							} else if (Global.TRACKING_MUDS.equals(argument.key)) {
								builder.append(company.separator + argument.value + (company.equalizer != null ? company.equalizer : "")
										+ CommonUtil.encodingUTF8(sendEvent.muds, argument, company));
							} else {
								builder.append(company.separator + argument.value + (company.equalizer != null ? company.equalizer : "")
										+ CommonUtil.encodingUTF8(params.get(argument.key), argument, company));
							}
						}
					}
					List<String> requiredEventValue = new ArrayList<String>();
					builder = new StringBuilder(CommonUtil.removeExistEvent(builder.toString(), requiredEventValue, separator, equalizer));
					builder.append(valueAndRedirectURL);
					if (company.signature != null && company.signature.paramKey != null) {
						String signatureString = CommonUtil.getSignature(context, builder.toString());
						builder.append(company.separator + company.signature.paramKey + (company.equalizer != null ? company.equalizer : "")
								+ CommonUtil.encodingUTF8(signatureString));
					}

					Logger.d("mma_request_url" + builder.toString());
					SharedPreferencedUtil.putLong(context, SharedPreferencedUtil.SP_NAME_NORMAL, builder.toString().trim(),
							getExpirationTime(company, sendEvent.getTimestamp()));
				} else {
					Logger.d("domain不匹配" + hostUrl + " company.domain.url:" + company.domain.url);
				}

			}
		}
	}

	public void recordEventWithUrl(String url) {
		boolean isEmulator = DeviceInfoUtil.isEmulator(context);
		if (isEmulator) {
			Logger.d("模拟器不记录，不发送数据");
			return;
		}
		SendEvent sendEvent = new SendEvent();
		sendEvent.setTimestamp(System.currentTimeMillis());
		sendEvent.setUrl(url);
		recordEvent(sendEvent);
		SharedPreferences sharedPreferences = SharedPreferencedUtil.getSharedPreferences(context, SharedPreferencedUtil.SP_NAME_NORMAL);
		if (sharedPreferences.getAll().keySet().size() >= Global.OFFLINECACHE_LENGTH) {
			SendEventMessage.getSendEventMessage(context).sendNromalList();
		}
	}

	/**
	 * 获得超时时间,默认时间：一天（60*60*24 * 1000）
	 * 
	 * @param company
	 * @param timeStamp
	 * @return
	 */
	private long getExpirationTime(Company company, Long timeStamp) {
		long result = 0;
		if (company.sswitch.offlineCacheExpiration != null) {
			result = Long.parseLong(company.sswitch.offlineCacheExpiration.trim()) * 1000 + timeStamp;
		} else {
			result = 60 * 60 * 24 * 1000 + timeStamp;
			// result = 60 * 2 * 1000 + timeStamp;
		}
		return result;
	}

}
